package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.Output;
/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * <pre>
 * 	<xsd:element name="attachments">
 * 		<xsd:complexType>
 * 			<xsd:sequence>
 * 				<xsd:element ref="componentRef" minOccurs="1" maxOccurs="unbounded"/>
 * 			</xsd:sequence>
 * 			<xsd:attributeGroup ref="coreopt"/>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 */
public final class Attachments extends CoreOptImpl {

	public static final String ELEMENT = "attachments";
	
	// Mandatory (min 1).
	private final List<ComponentRef> _componentRefs = new ArrayList<ComponentRef>(4);

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		for (int i = 0, n = _componentRefs.size(); i < n; i++) {
			_componentRefs.get(i).writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		super.readExternal(in);
		ComponentRef componentRef;
		int eventType = in.readNext();
		while (true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				if (ComponentRef.ELEMENT == in.getLocalName()) {
					_componentRefs.add(componentRef = new ComponentRef());
					componentRef.readExternal(in);
				}
				break;
			case InputConstants.END_ELEMENT:
				if (ELEMENT == in.getLocalName()) {
					return;
				}
			}
			eventType = in.readNext();
		}
	}
	
	
}